package com.feng.run;

import com.feng.entity.Article;
import com.feng.service.ArticleService;
import com.feng.utils.Const;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ViewCountRunning implements ApplicationRunner {

    final
    ArticleService articleService;

    final
    RedisTemplate  redisTemplate;

    public ViewCountRunning(ArticleService articleService, RedisTemplate redisTemplate) {
        this.articleService = articleService;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<Article> articles = articleService.list();
        Map<String, Long> map = articles.stream().parallel()
                .collect(Collectors.toMap(article -> article.getId(), article -> article.getViewCount()));
        redisTemplate.opsForHash().putAll(Const.REDIS_VIEW_COUNT_KET, map);
    }
}
